package search;

public class BinarySearch {
    private static int count = 0;

    public static void main(String[] args) {
        int index;
        int[] arr = new int[]{10, 2, 5, 11, 17, 21, 23, 23, 31, 37, 40};

        int key = 21;

        index = binarySearch(arr, key, 1, arr.length - 1);
        if(index != -1)
            System.out.println(key + " is in the index: " + index);
        else
            System.out.println(key + " is not in this array.");

        System.out.println("search Depth: " + count);
    }

    private static int binarySearch(int[] arr, int key, int low, int high) {
        if (low < high) {
            int mid = (low + high) / 2;
            count++;
            if (arr[mid] == key) {
                return mid;
            } else if(arr[mid] > key) {
                return binarySearch(arr, key, low, mid - 1);
            } else {
                return binarySearch(arr, key, mid + 1, high);
            }
        } else if(low == high) {
            return low;
        }
        return -1;
    }
}
